define [
	'jquery'
	'sammy/plugins/sammy.template-0.7.1.min.js'
	'jquery.couch.js'
	'helper'
], ($, undef, undef, H) ->
	S = {}
	$.fn.mb_history = (SamCtx) ->

		# --- Global Variables and Function ---------------
		
			_dID = ""
			$this = $(@)
			S = SamCtx
			$tpl = $('<tr>').html '
					<td><%= num+1 %></td>
					<td><%= donation_date%></td>
					<td>$<%= donation_amount %></td>'	

		# --- Core code of plugin -------------------------
	
			unless @mb_plugin()
				@mb_plugin 'history'
			
				# Initialization, adds table
				$this.find('.content').append("
					<table class='records'>
						<tbody>
							<tr>
								<th> Record </th>
								<th> Date </th>
								<th> Amount </th>
							</tr>
						</tbody>
					</table>")
				$.subscribe "mb.query", (e, arg) ->
					_type = arg['search_type']
					$this.find(".add.#{_type}").show()
					$this.find(".add:not(.#{_type})").hide()
								
				# Main subscription to obtain a donor_id
				$.subscribe "mb.donor", (e, arg) ->
					_dID = arg['donor_id']
					
					# Remove all non-header table rows (cleans the table)
					$this.find('.content tr:not(:has(th))').remove()
				
					# Query for all donation records using the donor_id
					$.couch.db("vcn-members").view 'app/donations', {key: _dID, success: (data) -> 
					
						# Create an empty array, then copy all of value object into this array
						# This is done so sorting can be accomplished
						recordlist = []
						recordlist[i] = data.rows[i].value for i of data.rows
					
						# Sort the array by donation date starting from most recent
						# Loop through this array and display the table of donations
						for i of recordlist.sort(H.sortby("donation_date", true))
							x = recordlist[i]
							content = S.content $tpl,
									num: Number(i)
									donation_date: x.donation_date
									donation_amount: x.donation_amount
							$this.find('.content tbody').append $('<tr>')
								.attr('id', x._id)
								.attr('index', Number(i)+1)
								.append content

						$this.find('.content').css('width', "#{$this.find('.content table').width()+40}px")
						}
					
					return # return for the subscription


			# --- Button Event Handlers ------------------
				
				$this.find('[name="add_donation"]').on 'click', ->
					if $this.find('select.add').is(":hidden")
						type = "org"
					else
						switch $this.find('select.add').val()
							when "non-member" then type = "ind.a"
							when "low-income" then type = "ind.b"
							when "personal" then type = "ind.c"
							when "family" then type = "ind.d"
					$.publish "mb.add_donation", {donor_id : _dID, type: type}
					S.app.setLocation "#/add_donation"
					return false
			
				# When a table row is clicked on, change background color to gray 
				# to mimic the "select" of options in an HTML selector, also modify the
				# selected row to have a classname of "selected"
				$this.find('.content table').on "mousedown", 'tr:not(:has(th))', ->
					$.publish "mb.donation", {id: $(@).attr('id')}
					S.app.setLocation "#/donation_detail"
					return
	
		return @
	return
